/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.sun.courier.view;

import com.sun.courier.dal.CourierDAL;
import com.sun.courier.dal.CourierManageDAL;
import com.sun.courier.dal.DepartmentDAL;
import com.sun.courier.dal.EmployeeDAL;
import com.sun.courier.dto.Courier_CourierManageDTO;
import com.sun.courier.dto.Employee_EmpLoginDTO;
import com.sun.courier.entity.Courier;
import com.sun.courier.entity.CourierManage;
import com.sun.courier.entity.Department;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Vector;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author HONG QUAN
 */
public class StoreExportActions extends JDialog implements ActionListener{

    CourierDAL cDal = new CourierDAL();
    CourierManageDAL cmDal = new CourierManageDAL();
    
    JPanel pnMain = new JPanel();
    JPanel pnTitle = new JPanel();
    JPanel pnCenter = new JPanel();
    JPanel pnButton = new JPanel();

    JLabel lblTitle = new JLabel("Export Couriers");
    JLabel lblCourierId = new JLabel("Courier Id");
    JLabel lblCourierName = new JLabel("Courier Name");
    JLabel lblCustomerName = new JLabel("Customer Name");
    JLabel lblPhone = new JLabel("Phone");
    JLabel lblWeight = new JLabel("Weight");
    JLabel lblDepartLocation = new JLabel("Departed Location");
    JLabel lblDestination = new JLabel("Destination");
    JLabel lblDistance = new JLabel("Distance");
    JLabel lblSender = new JLabel("Sender");
    JLabel lblReceiver = new JLabel("Receiver");
    JLabel lblDescription = new JLabel("Description");
    
    JTextField txtCourierId = new JTextField();
    JTextField txtCourierName = new JTextField();
    JTextField txtCustomerName = new JTextField();
    JTextField txtPhone = new JTextField();
    JTextField txtWeight = new JTextField();
    JTextField txtDepartLocation = new JTextField();
    JTextField txtDestination = new JTextField();
    JTextField txtDistance = new JTextField();
    JTextField txtSender = new JTextField();
    JTextField txtSenderShow = new JTextField();
    JTextField txtReceiver = new JTextField();
    JTextArea txtDescription = new JTextArea();
    
    JButton btnConfirm = new JButton("Export");
    
    private JTable table;
    ListSelectionModel listSelectionModel;
    DefaultTableModel model = null;
    int row = -1;
    private int ind = -1;
    
    public StoreExportActions(DefaultTableModel model, int row) {
        this.model = model;
        this.row = row;
        registerListeners();
        createControlPanel();
    }

    public void createControlPanel(){
        pnTitle.setLayout(new FlowLayout());
        pnTitle.setBorder(BorderFactory.createEtchedBorder());
        lblTitle.setFont(new Font("Arial", Font.BOLD, 25));
        pnTitle.add(lblTitle);

        GridBagLayout gridbag = new GridBagLayout();
        GridBagConstraints c = new GridBagConstraints();
        pnCenter.setBorder(BorderFactory.createEtchedBorder());
        pnCenter.setLayout(gridbag);

        c.gridx = 0;
        c.gridy = 0;
        c.gridheight = 1;
        c.insets = new Insets(5, 3, 3, 3);
        c.anchor = GridBagConstraints.SOUTHWEST;
        pnCenter.add(lblCourierId, c);

        c.gridx = 1;
        c.gridy = 0;
        c.gridheight = 1;
        c.insets = new Insets(5, 3, 0, 3);
        c.anchor = GridBagConstraints.SOUTHWEST;
        txtCourierId.setEditable(false);
        txtCourierId.setPreferredSize(new Dimension(300, 30));
        pnCenter.add(txtCourierId, c);

        c.gridx = 0;
        c.gridy = 1;
        pnCenter.add(lblCourierName, c);

        c.gridx = 1;
        c.gridy = 1;
        txtCourierName.setEditable(false);
        txtCourierName.setPreferredSize(new Dimension(300, 30));
        pnCenter.add(txtCourierName, c);

        c.gridx = 0;
        c.gridy = 2;
        pnCenter.add(lblCustomerName, c);

        c.gridx = 1;
        c.gridy = 2;
        txtCustomerName.setEditable(false);
        txtCustomerName.setPreferredSize(new Dimension(300, 30));
        pnCenter.add(txtCustomerName, c);

        c.gridx = 0;
        c.gridy = 3;
        pnCenter.add(lblPhone, c);

        c.gridx = 1;
        c.gridy = 3;
        txtPhone.setEditable(false);
        txtPhone.setPreferredSize(new Dimension(300, 30));
        pnCenter.add(txtPhone, c);

        c.gridx = 0;
        c.gridy = 4;
        pnCenter.add(lblWeight, c);

        c.gridx = 1;
        c.gridy = 4;
        txtWeight.setEditable(false);
        txtWeight.setPreferredSize(new Dimension(300, 30));
        pnCenter.add(txtWeight, c);

        c.gridx = 0;
        c.gridy = 5;
        pnCenter.add(lblDepartLocation, c);

        c.gridx = 1;
        c.gridy = 5;
        txtDepartLocation.setEditable(false);
        txtDepartLocation.setPreferredSize(new Dimension(300, 30));
        pnCenter.add(txtDepartLocation, c);

        c.gridx = 0;
        c.gridy = 6;
        pnCenter.add(lblDestination, c);

        c.gridx = 1;
        c.gridy = 6;
        txtDestination.setEditable(false);
        txtDestination.setPreferredSize(new Dimension(300, 30));
        pnCenter.add(txtDestination, c);

        c.gridx = 0;
        c.gridy = 7;
        pnCenter.add(lblDistance, c);

        c.gridx = 1;
        c.gridy = 7;
        txtDistance.setEditable(false);
        txtDistance.setPreferredSize(new Dimension(300, 30));
        pnCenter.add(txtDistance, c);

        c.gridx = 0;
        c.gridy = 8;
        pnCenter.add(lblSender, c);
        c.gridx = 1;
        c.gridy = 8;
        txtSenderShow.setEditable(false);
        txtSenderShow.setPreferredSize(new Dimension(300, 30));
        pnCenter.add(txtSenderShow, c);
        
        c.gridx = 0;
        c.gridy = 9;
        pnCenter.add(lblReceiver, c);
        c.gridx = 1;
        c.gridy = 9;
        txtReceiver.setPreferredSize(new Dimension(300, 30));
        pnCenter.add(txtReceiver, c);
        txtReceiver.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                StoreExportActions.PassReceiverActions par = new StoreExportActions.PassReceiverActions();
                par.setBackground(Color.GRAY);
                par.setModal(true);
                par.setAlwaysOnTop(true);
                par.setSize(new Dimension(700, 330));
                par.setVisible(true);
            }
        });
        
        c.gridx = 0;
        c.gridy = 10;
        c.anchor = GridBagConstraints.BELOW_BASELINE_LEADING;
        pnCenter.add(lblDescription, c);
        c.gridx = 1;
        c.gridy = 10;
        txtDescription.setBorder(BorderFactory.createLineBorder(Color.GRAY));
        txtDescription.setPreferredSize(new Dimension(300, 80));
        pnCenter.add(txtDescription, c);
        //Hide Sender id
        c.gridx = 1;
        c.gridy = 8;
        txtSender.setVisible(false);
        txtSender.setPreferredSize(new Dimension(300, 30));
        pnCenter.add(txtSender, c);
        
        pnButton.setLayout(new FlowLayout());
        pnButton.setBorder(BorderFactory.createEtchedBorder());
        pnButton.add(btnConfirm);

        pnMain.setLayout(new BorderLayout());
        pnMain.setBackground(Color.LIGHT_GRAY);
        pnMain.setBorder(BorderFactory.createRaisedSoftBevelBorder());
        pnMain.add(pnTitle, BorderLayout.NORTH);
        pnMain.add(pnCenter, BorderLayout.CENTER);
        pnMain.add(pnButton, BorderLayout.SOUTH);

        getContentPane().add(pnMain, BorderLayout.CENTER);
    }
    
    public void setValues(ArrayList<Courier_CourierManageDTO> lst) {

        txtCourierId.setText(Integer.toString(lst.get(0).getCm().getCourierId()));
        txtCourierName.setText(lst.get(0).getC().getCourierName());
        txtCustomerName.setText(lst.get(0).getC().getCustomerName());
        txtPhone.setText(lst.get(0).getC().getPhone());
        ArrayList<Courier> clst = new ArrayList<>();
        clst = cDal.getCourierInformationById(lst.get(0).getCm().getCourierId());
        txtWeight.setText(clst.get(0).getWeight());
        txtDepartLocation.setText(clst.get(0).getDepartLocation());
        txtDestination.setText(clst.get(0).getDestination());
        txtDistance.setText(clst.get(0).getDistance());
        txtSender.setText(Integer.toString(lst.get(0).getCm().getSender()));
        txtSenderShow.setText(cDal.getEmployeeName(lst.get(0).getCm().getSender()));
    }
    
    private void registerListeners() {
        btnConfirm.addActionListener(this);
    }
    
    @Override
    public void actionPerformed(ActionEvent e) {
        if(txtReceiver.getText().isEmpty()){
            JOptionPane.showMessageDialog(pnCenter, "You can not blank Receiver!", "Result", JOptionPane.INFORMATION_MESSAGE);
            return;
        }else{
            exportCourierToDespatching();
        }
    }

    private void exportCourierToDespatching() {
        CourierManage cm = new CourierManage();
        cm.setCourierId(Integer.parseInt(txtCourierId.getText()));
        cm.setSender(Integer.parseInt(txtSender.getText()));
        int receiverId = cDal.getEmployeeIdByUsername(txtReceiver.getText());
        cm.setReceiver(receiverId);
        cm.setDescription(txtDescription.getText());
        Date dNow = new Date();
        SimpleDateFormat ft = new SimpleDateFormat("MM/dd/yyyy");
        cm.setUpdatetime(ft.format(dNow));
        Boolean rs = cmDal.exportCourierToDespatching(cm);
        if (rs) {
            JOptionPane.showMessageDialog(pnCenter, "Export Successful!", "Result", JOptionPane.INFORMATION_MESSAGE);
            model.removeRow(row);
            this.dispose();
        } else {
            JOptionPane.showMessageDialog(pnCenter, "Export Fail!", "Result", JOptionPane.INFORMATION_MESSAGE);
        }
    }
    //Inner Class
    private class PassReceiverActions extends JDialog implements ActionListener {

        JPanel pnMainInner = new JPanel();
        JPanel pnCenterInner = new JPanel();
        JPanel pnButtomInner = new JPanel();
        JComboBox cbDespatching;
        Vector modelDespatching;
        JButton btnAdd = new JButton("Add");

        ArrayList<Department> lstDespatching = new ArrayList<>();
        ArrayList<Employee_EmpLoginDTO> lstDto = new ArrayList<>();
        DepartmentDAL dDal = new DepartmentDAL();
        EmployeeDAL eDal = new EmployeeDAL();
        String[] columnNames = {"Employee Name", "User Name", "Address", "Phone"};
        String[][] tableData = new String[1][4];
        ListSelectionModel listSelectionModel;
        JScrollPane tablePane;
        private TablePanel gregsPanel = new TablePanel("", tableData, columnNames);

        public PassReceiverActions() {

            lstDespatching = dDal.showAllDespatching();
            lstDto = eDal.getAllDespatchingEmployee();
            createStoreControl();
            registerActionListener();
        }

        private void createStoreControl() {
            modelDespatching = showAllDespatchingCombo();
            cbDespatching = new JComboBox(modelDespatching);
            cbDespatching.setPreferredSize(new Dimension(300, 30));
            pnCenterInner.add(cbDespatching, BorderLayout.PAGE_START);
            pnCenterInner.add(gregsPanel.getMainPanel(), BorderLayout.CENTER);
            setLayout(new BorderLayout());
            pnButtomInner.add(btnAdd);
            
            pnMainInner.setLayout(new BorderLayout());
            pnMainInner.setBackground(Color.LIGHT_GRAY);
            pnMainInner.add(pnCenterInner, BorderLayout.CENTER);
            pnMainInner.add(pnButtomInner, BorderLayout.SOUTH);
            getContentPane().add(pnMainInner, BorderLayout.CENTER);
        }

        private Vector showAllDespatchingCombo() {
            Vector modelct = new Vector();
            modelct.add(0, "Choose A Department");
            for (int i = 0; i < lstDespatching.size(); i++) {
                modelct.addElement(new StoreExportActions.Item(lstDespatching.get(i).getDepId(), lstDespatching.get(i).getDepartmentName().toString()));
            }
            return modelct;
        }
        
        private void registerActionListener() {
            cbDespatching.addActionListener(this);
            btnAdd.addActionListener(this);
        }
        
        @Override
        public void actionPerformed(ActionEvent e) {
            String[][] newdata = new String[lstDto.size()][4];
            Item item = (Item) cbDespatching.getSelectedItem();
            int depId = item.getId();
            if (e.getSource().equals(cbDespatching)) {
                int j = 0;
                for (int i = 0; i < lstDto.size(); i++) {
                    if (lstDto.get(i).getE().getDepId() == depId) {
                        newdata[j][0] = lstDto.get(i).getE().getEmployeeName();
                        newdata[j][1] = lstDto.get(i).getL().getUsername();
                        newdata[j][2] = lstDto.get(i).getE().getAddress();
                        newdata[j][3] = lstDto.get(i).getE().getPhone();
                        j = j + 1;
                    }
                }
                gregsPanel.setTableModelDataVector(newdata, columnNames);
                gregsPanel.fireTableDataChanged();
            } else if (e.getSource().equals(btnAdd)) {
                txtReceiver.setText(table.getValueAt(ind, 1).toString());
                this.dispose();
            }
        }
    }
    
    class TablePanel {

        private JPanel mainPanel = new JPanel();
        private DefaultTableModel dm;
        private JScrollPane scrollpane;

        public TablePanel(String title, Object[][] data, Object[] columnNames) {
            table = new JTable();
            dm = new DefaultTableModel(data, columnNames);
            table.setModel(dm);
            listSelectionModel = table.getSelectionModel();
            listSelectionModel.addListSelectionListener(new StoreExportActions.SharedListSelectionHandler());
            table.setSelectionModel(listSelectionModel);
            table.setRowHeight(30);
            scrollpane = new JScrollPane(table);
            mainPanel.setBorder(BorderFactory.createTitledBorder(title));
            mainPanel.setLayout(new BorderLayout(1, 1));
            mainPanel.setPreferredSize(new Dimension(600, 200));
            mainPanel.add(scrollpane, BorderLayout.CENTER);
        }

        public void setTableModelDataVector(Object[][] data, Object[] columnNames) {
            dm.setDataVector(data, columnNames);
        }

        public void fireTableDataChanged() {
            dm.fireTableDataChanged();
        }

        public JScrollPane getScrollPane() {
            return scrollpane;
        }

        public JComponent getMainPanel() {
            return mainPanel;
        }
    }
    
    class Item {

        private int id;
        private String description;

        public Item(int id, String description) {
            this.id = id;
            this.description = description;
        }

        public int getId() {
            return id;
        }

        public String getDescription() {
            return description;
        }

        public String toString() {
            return description;
        }
    }

    class SharedListSelectionHandler implements ListSelectionListener {

        public void valueChanged(ListSelectionEvent e) {
            ListSelectionModel lsm = (ListSelectionModel) e.getSource();

            int firstIndex = e.getFirstIndex();
            int lastIndex = e.getLastIndex();
            boolean isAdjusting = e.getValueIsAdjusting();
            if (lsm.isSelectionEmpty()) {

            } else {
                // Find out which indexes are selected.
                int minIndex = lsm.getMinSelectionIndex();
                int maxIndex = lsm.getMaxSelectionIndex();
                for (int i = minIndex; i <= maxIndex; i++) {
                    if (lsm.isSelectedIndex(i)) {
                        ind = i;
                    }
                }
            }
        }
    }
}
